package com.deepblue.okhttp;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.img)
    ImageView mImageView;
    @BindView(R.id.btn)
    Button mButton;
    @BindView(R.id.tv)
    TextView mTextView;
    private String tvStr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initEvent();
    }

    /**
     * 事件的初始化
     */
    private void initEvent() {
        //添加点击事件，去取网络数据
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                getByUrl("http://square.github.io/okhttp/");
//                mTextView.setText(tvStr);
                getByUrl("http://avatar.csdn.net/A/1/7/1_liuhongwei123888.jpg");

            }
        });
    }

    private void getByUrl(String url) {

        new AsyncTask<String, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(String... params) {
                String urls = params[0];
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url(urls).build();
                Response response = null;
                String responseStr = null;
                Bitmap bitmap = null;
                try {
                    response = client.newCall(request).execute();

                    bitmap = BitmapFactory.decodeStream(response.body().byteStream());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                mImageView.setImageBitmap(bitmap);

            }
        }.execute(url);

    }
}
